from common.models.award_project import AwardProject
from common.models.award_detail import AwardDetail
from flask import Blueprint, request, make_response, redirect
from config.dingtalk_setting import AppKey, AppSecret, AgentId, role_hr, bpmid
from dingtalk import SecretClient, model
import json, requests
from application import app, db
from common.libs.DataHelper import getCurrentTime
from common.models.salary_ded import SalaryDed
import datetime
from common.libs.Helper import dingtalkpost
from config.dingtalk_setting import column
from common.models.user import User
from common.libs.SQLTransform import queryToDict
from sqlalchemy import and_, or_
import urllib.parse

##连接
client = SecretClient(AppKey, AppSecret)  # 新 access_token 获取方式

salary_page = Blueprint("salary_page", __name__)


@salary_page.route("/addded", methods=['GET', 'POST'])
def addded():
    userid = request.json.get('userid')
    child = request.json.get('child')
    study = request.json.get('study')
    parent = request.json.get('parent')
    house = request.json.get('house')
    rent = request.json.get('rent')
    sick = request.json.get('sick')
    lilchildfund = request.json.get('lilchildfund')
    year = request.json.get('year')

    ded=SalaryDed.query.filter_by(userid=userid).filter_by(year=year).first()
    if ded :
        ded.child=child
        ded.parent=parent
        ded.house=house
        ded.rent=rent
        ded.sick=sick
        ded.study=study
        ded.lilchirdfund=lilchildfund
        ded.updated_time=getCurrentTime()
        db.session.commit()
    else:
        ded=SalaryDed()
        ded.userid=userid
        ded.year=year
        ded.child = child
        ded.parent = parent
        ded.house = house
        ded.rent = rent
        ded.sick = sick
        ded.study = study
        ded.lilchirdfund = lilchildfund
        ded.created_time = getCurrentTime()
        db.session.add(ded)
        db.session.commit()

    return json.dumps({"msg": "成功"}, ensure_ascii=False)






@salary_page.route("/getprojectlist", methods=['GET', 'POST'])
def getprojectlist():
    userid = request.json.get('id')

    priject = AwardProject.query.filter_by(creater=userid).order_by(AwardProject.created_time.desc()).all()

    rts = []
    for item in priject:
        temp = dict(id=item.id, name=item.name, sn=item.sn, created_time=str(item.created_time),
                    username=item.username.name, status=item.status)
        rts.append(temp)

    return json.dumps(rts, ensure_ascii=False)


@salary_page.route('/sendded', methods=['GET', 'POST'])
def sendded():
    # list = [857, 739]
    # renyuan = User.query.filter(
    #     User.id == 739).all()

    today = datetime.datetime.today()
    year = today.year-1


    renyuan = User.query.filter(
        or_(User.status == 4, User.status == 1)).filter(User.id == 225).all()

    userlist = []
    for i in renyuan:
        userlist.append(i.userid)

    for i in userlist:
        user = User.query.filter_by(userid=i).first()
        id = str(user.id)
        name = user.name

        base_url = 'http://101.132.227.54:88/salarycollect?id=' + id+'&year='+str(year)
        encodeurl = urllib.parse.quote(base_url)

        dingtalkurl = "dingtalk://dingtalkclient/action/openapp?corpid=ding5b2aa85601c5363fffe93478753d9884&container_type=work_platform&app_id=0_1784691312&redirect_type=jump&redirect_url=" + encodeurl
        normalurl = "dingtalk://dingtalkclient/page/link?url=" + encodeurl + "&pc_slide=true"

        msg = {
            "msgtype": "action_card",
            "action_card": {
                "title": "专项附加扣除信息收集",
                "markdown": "![](http://upload.guanzhuoran.cn/collect.png) \n ### 专项附加扣除信息收集  \n   ##### 工号:" + id + "   姓名:" + name  + "\n ##### 统计年份:"+str(year) + '年',
                "btn_orientation": "1",
                "btn_json_list": [
                    # {
                    #     "title": "完善信息(PC)",
                    #     "action_url": dingtalkurl,
                    # },
                    {
                        "title": "开始填报",
                        "action_url": normalurl,
                    },

                ]
            }
        }

        a = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=i.split())

    return json.dumps("成功推送", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)






